package com.gitee.common.data.tree.node;

import java.util.Arrays;

public abstract class MoreFrontTreeItemNodeImpl extends AbstractTreeItemNode implements MoreFrontTreeItemNodeI {

    private TreeItemNodeI[] fronts;

    private int frontCap = 3;

    @Override
    public int getFrontLength() {
        return fronts == null ? 0 : fronts.length;
    }

    @Override
    public TreeItemNodeI[] getFronts() {
        return fronts;
    }

    @Override
    public void changeFront(TreeItemNodeI older, TreeItemNodeI newer) {
        if (fronts != null) {
            TreeItemNodeI node = fetchInFronts(older);
            node = newer;
        }
    }

    @Override
    public void appendTo(TreeItemNodeI front) {
        if (front == null) {
            return ;
        }
        if ( fetchInFronts(front) != null ) {
            return ;
        }
        if (fronts == null) {
            fronts = new TreeItemNodeI[frontCap];
        } else {
            if (fronts.length >= frontCap) {
                fronts = Arrays.copyOf(fronts, frontCap * 2);
            }
        }

        fronts[fronts.length] = front;
    }

    @Override
    public void setFrontCap(int frontCap) {
        if (frontCap > 0) {
            this.frontCap = frontCap;
        }
    }

    @Override
    public TreeItemNodeI searchFront(String id) {
        if (fronts == null || id == null) {
            return null;
        }
        for (TreeItemNodeI front : fronts) {
            if (id.equals(front.getId())) {
                return front;
            }
            if (front instanceof FrontTreeItemNodeI) {
                return ((FrontTreeItemNodeI) front).searchFront(id);
            }
        }
        return null;
    }

    @Override
    public void deleteFront(TreeItemNodeI node) {
        if (node != null && this.fronts != null) {
            TreeItemNodeI nodeI = fetchInFronts(node);
            nodeI = null;
        }
    }

    protected TreeItemNodeI fetchInFronts(TreeItemNodeI nodeI) {
        if (fronts == null) {
            return null;
        }
        for (TreeItemNodeI node : fronts) {
            if (node.compareTo(nodeI) == 0) {
                return node;
            }
        }
        return null;
    }
}
